import '../public/index'
import url from '../data/url'
import {getUrlParam} from '../data/util'
import request from '../data/request'
import {header} from '../data/config'
import store from 'store'
import {
  checkBuildIn as valid_checkBuildIn,
  checkBuildOut    as valid_checkBuildOut,
} from '../data/validate'

const base             = url.base,
      getDevLibList    = request.getDevLibList,
      editBuildLibInfo = request.editBuildLibInfo,
      getProvinceList  = request.getProvinceList,
      getCityList      = request.getCityList;

// 页面标题
const title  = '楼盘库管理',
      action = '修改';

let form = new Vue({
  el: '#form',
  data: () => {
    return ({
      id: '',
      dId: '',
      dIdList: [],
      province: '',
      provinceList: [],
      city: '',
      cityList: [],
      area: '',
      areaList: [],
      reserveName: '',
      propertyName: '',
      openUp: 'close',
      isLock: true
    })
  },
  watch: {
    province: function (val, oldVal) {
      this.getCityList(val, _.findIndex(this.provinceList, (item) => (item.id === this.province)))
    },
    cityList: function (val, oldVal) {
      // 初始化时显示用户之前填写的数据
      if (!this.isCityInit) {
        this.city       = store.get('storeData').buildingInfo.city;
        this.isCityInit = true;

        return
      }

      // 默认显示第一条数据
      if (val.length) {
        this.city = val[0].id
      }
    },
    city: function (val, oldVal) {
      this.getAreaList(val)
    },
    areaList: function (val, oldVal) {
      // 初始化时显示用户之前填写的数据
      if (!this.isAreaInit) {
        this.area       = store.get('storeData').buildingInfo.area;
        this.isAreaInit = true;

        return
      }

      // 默认显示第一条数据
      if (val.length) {
        this.area = val[0].id
      }
    }
  },
  mounted: function () {

    let that = this,
        id   = getUrlParam('id');

    if (!id) {
      layer.msg('未获取到id,将跳转到分页页面', {
        icon: 5
      });

      setTimeout(() => {
        window.location = './index.html'
      }, 1000);

      return
    }

    this.id = id;

    let loading = layer.msg('初始化数据中...', {
      icon: 16,
      time: 0
    });

    Promise
      .all([this.getDev(), this.getProvinceList()])
      .then((res) => {

        layer.close(loading);

        that.isLock       = false;
        that.dIdList      = res[0].object;
        that.provinceList = res[1].object;

        console.log(res[0]);

        let storeData = store.get('storeData')

        console.log(storeData)

        if (!storeData) {
          layer.msg('页面跳转错误', {
            icon: 5
          })

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)

          return
        }

        $.extend(that.$data, storeData, {
          dId: storeData.buildingInfo.dId,
          province: storeData.buildingInfo.province,
          reserveName: storeData.buildingInfo.reserveName,
          propertyName: storeData.buildingInfo.propertyName,
          openUp: storeData.buildingInfo.openUp,
        });


        valid();


        setTimeout(() => {

          that.initSelect();

        }, 0)
      })
      .catch((error) => {
        console.log(error);

        layer.close(loading);
        layer.msg(error || '初始化数据失败', {
          icon: 5
        })
      })
  },
  methods: {
    // 获取开发商列表
    getDev: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getDevLibList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取省列表
    getProvinceList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getProvinceList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取城市列表
    getCityList: function (id, index) {
      let that = this

      // 检测index有效性
      if (!(/^\d+$/.test(index)) && index < 0) {
        return
      }

      // 如果已请求过数据则直接读取缓存的数据
      if (this.provinceList[index].cityList) {
        that.cityList = this.provinceList[index].cityList
        return
      }

      let loading = layer.msg('获取数据中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        url: base + getCityList,
        headers: header,
        data: {
          provinceId: id || 1
        }
      })
        .done(function (res) {
          if (res.code === 0) {
            // 缓存数据到省市列表里
            that.cityList = that.provinceList[index].cityList = res.object
            return
          }

          layer.msg('初始化数据失败', {
            icon: 5
          })
        })
        .fail(function () {
          layer.msg('初始化数据失败', {
            icon: 5
          })
        })
        .always(function () {
          layer.close(loading)
        })
    },
    // 获取区域列表
    getAreaList: function (id) {
      let that = this

      let loading = layer.msg('获取数据中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        url: base + getCityList,
        headers: header,
        data: {
          provinceId: id || 1
        }
      })
        .done(function (res) {
          if (res.code === 0) {
            that.areaList = res.object
            return
          }

          layer.msg('初始化数据失败', {
            icon: 5
          })
        })
        .fail(function () {
          layer.msg('初始化数据失败', {
            icon: 5
          })
        })
        .always(function () {
          layer.close(loading)
        })
    },
    //初始化快捷下拉选择框
    initSelect: function () {
      let that = this;

      $(this.$refs.select)
        .selectize({
          onChange: function (val) {
            that.dId = val;
          }
        })
    }
  }
});

function valid() {

  let form_valid,
      $form = $('#form');

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!');

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      });

      form.isLock = true;

      let devName      = $.trim($(form.$refs.select).find('option:selected').text()),
          provinceName = $.trim($(form.$refs.province).find('option:selected').text()),
          cityName     = $.trim($(form.$refs.city).find('option:selected').text()),
          areaName     = $.trim($(form.$refs.area).find('option:selected').text());

      $.ajax({
        url: base + editBuildLibInfo,
        type: 'POST',
        headers: header,
        contentType: 'application/json',
        data: JSON.stringify({
          id: form.id,
          dId: form.dId + ',' + devName,
          province: form.province + ',' + provinceName,
          city: form.city + ',' + cityName,
          area: form.area + ',' + areaName,
          reserveName: form.reserveName,
          propertyName: form.propertyName,
          openUp: form.openUp
        })
      })
        .done(function (res) {
          console.log(res);

          if (res.code === -1) {
            layer.msg(res.message, {
              icon: 5
            });

            return
          }

          layer.msg(`${action}${ title }成功`, {
            icon: 6
          });

          // 重置表单
          $.extend(form.$data, form.$options.data());

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function (res) {
          console.log(res);

          layer.msg(`${action}${ title }失败`, {
            icon: 5
          });

          console.log("error");
        })
        .always(function (res) {

          layer.close(loading_modal);
          form.isLock = false

        })

    }
  });

  // 验证
  form_valid = $form.validate({
    errorPlacement: function (error, element) {
      error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      dId: {
        required: true
      },
      province: {
        required: true
      },
      city: {
        required: true
      },
      area: {
        required: true
      },
      reserveName: valid_checkBuildOut,
      propertyName: valid_checkBuildIn,
      openUp: {
        required: true
      }
    }
  });
}